<template>
  <el-dialog
    :title="`${isCreate ? '添加' : '编辑'}辅材`"
    :visible.sync="dialogVisible"
    class="dialog"
    width="400px">
    <el-form
      :model="formData"
      label-width="120px"
      ref="form"
      :rules="rules"
      size="small">
      <el-form-item label="二级分类名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="iconUrl">
        <uploader :src.sync="formData.iconUrl"></uploader>
      </el-form-item>
      <el-form-item label="所属一级分类" prop="parentId">
        <el-select v-model="formData.parentId" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <dialog-footer
      slot="footer"
      @cancel="dialogVisible = false"
      @confirm="confirm"
    />
  </el-dialog>
</template>
<script>
import { updateCategory, saveCategory } from '@/api/course';

export default {
  props: {
    initFormData: Object,
    isCreate: Boolean,
    options: Array,
  },
  data() {
    return {
      formData: {
        ...this.initFormData,
      },
      rules: {
        name: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
        parentId: [{ required: true, message: '所属一级分类不能为空', trigger: 'blur' }],
      },
      dialogVisible: false,
    };
  },
  watch: {
    initFormData(val) {
      this.formData = { ...val };
    },
  },
  methods: {
    confirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const { iconUrl } = this.formData;
          if (iconUrl) {
            if (this.isCreate) {
              await saveCategory(this.formData);
            } else {
              await updateCategory(this.formData);
            }
            this.dialogVisible = false;
            this.$emit('confirm', this.formData);
          } else {
            this.$message.error('图标不能为空');
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
  .dialog {
    ::v-deep .el-input__inner {
      width: 200px;
    }
  }
</style>
